﻿using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using ZGL.Api.Entity;

namespace ZGL.Api.Utils
{
    public class JwtHelper
    {
        public static string GenerateJsonWebToken(SysUser userInfo)
        {
            var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(TokenParameter.Secret));
            var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256);
            var claimsIdentity = new ClaimsIdentity(CookieAuthenticationDefaults.AuthenticationScheme);
            claimsIdentity.AddClaim(new Claim("userId", userInfo.UserId.ToString()));
            claimsIdentity.AddClaim(new Claim(ClaimTypes.Name, userInfo.Username));
            //claimsIdentity.AddClaim(new Claim(ClaimTypes.Role,userInfo.Username));
            var token = new JwtSecurityToken(TokenParameter.Issuer,
              TokenParameter.Audience,
              claimsIdentity.Claims,
              expires: DateTime.Now.AddMinutes(TokenParameter.AccessExpiration),
              signingCredentials: credentials);

            return new JwtSecurityTokenHandler().WriteToken(token);
        }
        /// <summary>
        /// 判断Token是否过期
        /// </summary>
        /// <param name="token"></param>
        /// <returns></returns>
        public static void ValidateToken(string token)
        {
            var tokenHandler = new JwtSecurityTokenHandler();
            var validationParameters = new TokenValidationParameters
            {
                ValidateIssuerSigningKey = true,
                IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(TokenParameter.Secret)),
                ValidateIssuer = true,
                ValidIssuer = TokenParameter.Issuer,
                ValidateAudience = true,
                ValidAudience = TokenParameter.Audience,
                ValidateLifetime = true,
                ClockSkew = TimeSpan.Zero
            };
            try
            {
                var principal = tokenHandler.ValidateToken(token, validationParameters, out var validatedToken);
                if (!principal.Identity.IsAuthenticated)
                {
                    throw new Exception("Token无效");
                }

                // Use the validated token
                var jwtToken = (JwtSecurityToken)validatedToken;
                // ...
            }
            catch (SecurityTokenException ex)
            {
                throw new Exception("处理token验证错误");

                // Handle token validation error
                // ...
            }
        }
    }
    public class TokenParameter
    {
        public const string Issuer = "lqwvje";//颁发者        
        public const string Audience = "LuoFenMing";//接收者    
        public const string Secret = "sadfasdffdgdsfgdfgdfgasdfasdgadtgreyhgrfhgfjtdghjgutyhfgdyhr";//签名秘钥        
        public const int AccessExpiration = 30;//AccessToken过期时间（分钟）
    }
}
